package beans;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import classes.Customer;
import database.pack.DatabaseConnector;

public class CustomerLoginBeanDAO implements Serializable 
{
	private static final long serialVersionUID = 1L;
	private boolean loginState = false;
	private Customer customer = new Customer();
	
	public void getLogin(String username, String password)
	{
		try
		{
			DatabaseConnector databaseConnect = new DatabaseConnector();
			databaseConnect.connectToDatabase();
			Statement stat = databaseConnect.getConnection().createStatement();
			// sql statement gets customer data from the username
			ResultSet res = stat.executeQuery("SELECT id,addressLine1,addressLine2,addressLine3,birthDate,emailAddress,firstName,"
								+ "goldMember,greeting,lastName,password,postcode,username FROM customer WHERE username = " + "'" + username + "'");
			if(res.next())
			{
				if((res.getString("username").equals(username)) && (res.getString("password").equals(password)))
				{
					// sets login state to true
					loginState = true;
					
					// set customer details
					customer.setId(res.getLong("id"));
					customer.setFirstName(res.getString("firstName"));
					customer.setLastName(res.getString("lastName"));
					customer.setBirthDate(res.getDate("birthDate"));
					Customer.setAddressLine1(res.getString("addressLine1"));
					Customer.setAddressLine2(res.getString("addressLine2"));
					Customer.setAddressLine3(res.getString("addressLine3"));
					customer.setGreeting(res.getString("greeting"));
					customer.setEmailAddress(res.getString("emailAddress"));
					customer.setGoldMember(res.getBoolean("goldMember"));
					customer.setPostcode(res.getString("postcode"));
					customer.setUsername(res.getString("username"));
					customer.setPassword(res.getString("password"));
				}
			}
			res.close();
			stat.close();
			databaseConnect.getConnection().close();
		}
		catch(SQLException exception)
		{
			System.out.println(exception.getMessage());
		}
		catch(ClassNotFoundException e)
		{
			System.out.println("Couldn't connect");
			e.printStackTrace();
		}
	}
	
	// Getters
	public boolean getLoginState()
	{
		return loginState;
	}
	
	public Customer getCustomer()
	{
		return customer;
	}
	
}
